﻿using System;
using System.Net.Sockets;
using System.Text;

namespace airwolf.HTTP
{
    public class Worker
    {
        public Worker(Server Server, TcpClient Client)
        {
            NetworkStream stream = Client.GetStream();
            byte[] buffer = new byte[1024];
            StringBuilder message = new StringBuilder();
            int bytes = 0;

            do
            {
                bytes = stream.Read(buffer, 0, buffer.Length);
                message.Append(Encoding.ASCII.GetString(buffer, 0, bytes));
            }
            while (stream.DataAvailable);

            System.Console.WriteLine("Received HTTP request: {0}", System.Text.RegularExpressions.Regex.Match(message.ToString(), @"^[^\r]+").Value);
            string msg = message.ToString();
            HTTPResult result = Server.Route(HTTPUtility.GetPath(msg), msg);
            string content = result.Content;
            string contentType = HTTPUtility.GetContentTypeString(result.ContentType);
            string date = Locale.Now;
            string response = String.Format("{0}\r\nContent-Length: {1}\r\nContent-Type: {2}\r\nServer: {3}\r\nDate: {4}\r\n\r\n{5}\r\n", result.Header, content.Length + 2, contentType, Server.Name, date, content);
//            HTTP/1.1 200 OK
//Content-Length: 5669
//Content-Type: text/xml; charset="utf-8"
//Server: Microsoft-Windows-NT/5.1 UPnP/1.0 UPnP-Device-Host/1.0 Microsoft-HTTPAPI/2.0
//Date: Sat, 27 Feb 2010 15:31:53 GMT

            byte[] responseBytes = System.Text.Encoding.ASCII.GetBytes(response);
            stream.Write(responseBytes, 0, responseBytes.Length);
            Client.Close();
        }
    }
}
